package cn.cxl.utils;

import android.app.Activity;
import android.content.Context;
import android.graphics.Rect;
import android.view.WindowManager;

import java.lang.reflect.Field;

public class DipPx {
	/**
	 * 根据手机的分辨率从 dp的单位转成为px(像素)
	 */
	public static int dip2px(Context context, float dpValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dpValue * scale + 0.5f);
	}

	/**
	 * 根据手机的分辨率从 px(像素)的单位转成为dp
	 */
	public static int px2dip(Context context, float pxValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (pxValue / scale + 0.5f);
	}
	
	/**
	 * 获取屏幕宽度
	 */
	public static int getScreenWidth(Context context) {
		WindowManager wm = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
		return wm.getDefaultDisplay().getWidth();
	}
	/**
	 * 获取状态栏的高
	 */
	public static int getStatusBarHeight(Activity context) {
		Rect frame = new Rect();
		context.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
		int statusBarHeight = frame.top;
		if(0 == statusBarHeight) {
			statusBarHeight = getStatusBarHeightByReflection(context);
		}
		return statusBarHeight;
	}

	public static int getStatusBarHeightByReflection(Context context) {
		Class<?> c;
		Object obj;
		Field field;
		// 默认为38，貌似大部分是这样的
		int x, statusBarHeight = 38;
		try {
			c = Class.forName("com.android.internal.R$dimen");
			obj = c.newInstance();
			field = c.getField("status_bar_height");
			x = Integer.parseInt(field.get(obj).toString());
			statusBarHeight = context.getResources().getDimensionPixelSize(x);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		return statusBarHeight;
	}
}
